/**
 * 
 */
package com.cnhaimei.vod.logic;

import java.util.ArrayList;
import java.util.HashMap;

import com.cnhaimei.vod.net.Request;
import com.cnhaimei.vod.net.Response;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 
 * @author jin001.wu@gmail.com <br>
 * @date 2011-7-20
 * 
 */
public class EventsManager {
	public static final Object lock = new Object();
	private static EventsManager global;
	private Handler mHandler;
	private HashMap<Integer, ArrayList<EventsListener>> eventMap = new HashMap<Integer, ArrayList<EventsListener>>();

	private EventsManager() {
		mHandler = new EventHandler();
	}

	public void registerListener(int event, EventsListener listener) {
		ArrayList<EventsListener> lst = eventMap.get(event);
		if (lst == null) {
			lst = new ArrayList<EventsListener>();
			eventMap.put(event, lst);
		}
		if (!lst.contains(listener) && (listener != null)) {
			lst.add(listener);
		}
	}

	public void unRegisterListener(int event, EventsListener listener) {
		ArrayList<EventsListener> lst = eventMap.get(event);
		if (lst != null) {
			lst.remove(listener);
		}
	}

	public void sendEvent(int event, Object response, boolean suc) {
		Message msg = mHandler.obtainMessage(event);
		msg.what = event;
		msg.arg1 = suc ? EventHandler.SUC : EventHandler.FAIL;
		msg.obj = response;
		mHandler.sendMessage(msg);
	}

	public static EventsManager G() {
		if (global == null) {
			synchronized (lock) {
				if (global == null) {
					synchronized (lock) {
						EventsManager g = new EventsManager();
						global = g;
					}
				}
			}
		}
		return global;
	}

	public interface EventsListener {
		void onEvent(int event, Object result, boolean isSuc);
	}

	public interface Event {
		int CONNECTING = -1;
		int DISCONNECT = -2;
		int UNDEFINE = 0;
		int ROOMS = 1;//请求包厢列表
		int CHCKD_PAS = 2;
		int ROOM_INFO = 3;//请求包厢ip
		int QUERY_RESPONSE = 4;
		int QUERY_RECORDS = 5;
		int PLYER_STATE = 6;
		int SELCT_SONGS = 7;
		int DONE_SONGS = 8;//已唱
		int SELCT_CHANG = 9;
		int DONE_CHANG = 10;
		int QUERY_CLOSE = 11;
		int QUERY_QUERY = 12;
		int REGISTER_ROOMS = 13;//请求注册包厢
		int SELECT_SONG_RESULT = 14; //点歌是否成功
	}

	private class EventHandler extends Handler {
		static final int SUC = 1;
		static final int FAIL = 0;

		@Override
		public void handleMessage(Message msg) {
			ArrayList<EventsListener> lst = eventMap.get(msg.what);

			try {
				if (lst == null || lst.isEmpty()) {
					return;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			for (int i = 0; i < lst.size(); i++) {
				Log.e("eventmanager", "manager");
				lst.get(i).onEvent(msg.what, msg.obj,
						msg.arg1 == SUC ? true : false);
			}
		}
	}

}
